<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DefApplicationModel } from '#/api';

import { ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DefApplicationApi } from '#/api';
import { Icon } from '#/components/icon';
import { TableAction } from '#/components/table-action';
import { ActionEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';

import DetailForm from './modules/detail.vue';
import EditForm from './modules/form.vue';
import { gridSchemas, searchFormSchemas } from './schemas/index';

const permCode = PermCode.devOperation.application.defApplication;
const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
};

const gridOptions: VxeGridProps<DefApplicationModel.DefApplicationResultVO> = {
  ...gridSchemas,
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page, sorts, filters }, formValues) => {
        const queryParams: any = { model: { ...formValues } };
        // 处理排序条件
        const firstSort = sorts[0];
        if (firstSort) {
          queryParams.sort = firstSort.field;
          queryParams.order = firstSort.order;
        }
        queryParams.size = page.pageSize;
        queryParams.current = page.currentPage;
        // 处理筛选条件
        filters.forEach(({ field, values }) => {
          queryParams[field] = values.join(',');
        });

        return DefApplicationApi.page(queryParams).then((r) => {
          r.total = Number(r.total);
          return r;
        });
      },
    },
  },
};

const editFormRef = ref();
const detailFormRef = ref();
const hasTopTableDropDownActions = ref(false);
const { createMessage } = useMessage();

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid?.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid?.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  formOptions,
  gridOptions,
});

const handleView = (record: any) => {
  detailFormRef.value.setData({
    record,
  });
  detailFormRef.value.open();
};

// 编辑
const handleEdit = (record: any, e: Event) => {
  e?.stopPropagation();
  editFormRef.value.setData({
    type: ActionEnum.EDIT,
    gridApi,
    record,
  });
  editFormRef.value.open();
};
// 复制
const handleCopy = (record: any, e: Event) => {
  e?.stopPropagation();
  editFormRef.value.setData({
    type: ActionEnum.COPY,
    gridApi,
    record,
  });
  editFormRef.value.open();
};

// 打开新增表单
const handleAdd = () => {
  editFormRef.value.setData({
    type: ActionEnum.ADD,
    gridApi,
  });
  editFormRef.value.open();
};

// 删除
const handleDelete = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row.id);
  } else {
    ids = gridApi.grid?.getCheckboxRecords().map((item) => item.id);
  }
  DefApplicationApi.remove(ids).then(() => {
    createMessage.success('删除成功');
    gridApi.reload();
  });
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              auth: [permCode.add],
              onClick: handleAdd.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              auth: [permCode.delete],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 8px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              size: 'small',
              onClick: handleView.bind(null, row),
            },
            {
              label: '编辑',
              auth: [permCode.edit],
              type: 'link',
              size: 'small',
              onClick: handleEdit.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: '复制',
              auth: [permCode.copy],
              onClick: handleCopy.bind(null, row),
            },
            {
              label: '删除',
              auth: [permCode.delete],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
    <DetailForm ref="detailFormRef" />
    <EditForm ref="editFormRef" />
  </Page>
</template>
